package com.wk.controller.student;

import com.wk.pojo.Friends;
import com.wk.pojo.User;
import com.wk.service.Userinfoservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @program: thesis
 * @description: 好友类
 * @author: 王侃
 * @create: 2020-03-07 17:57
 **/
@Controller
@RequestMapping("/stu")
public class Stufriendscontroller {

    @Autowired
    Userinfoservice userinfoservice;

    //跳转到好友搜索
    @RequestMapping("/friends/search")
    public String friend_search(String username, Model model)
    {
        List<User> users=new ArrayList<>();
        if (username==null||username=="")
        {
            model.addAttribute("users",users);
        }
        else {
            users=userinfoservice.selectbyusername_friends(username);
            model.addAttribute("users",users);
        }
        return "student/friends/search";
    }

    //添加为自己的好友
    @RequestMapping("/friends/add/{id}")
    public String friends_add(HttpSession session,@PathVariable("id")Integer id)
    {
        User me=(User)session.getAttribute("loginuser");
        //先查找是否已经是好友
        User he=userinfoservice.selectbyuserid(id);
        //如果还没有加好友，将自动添加好友，1，把他加为我的好友
        Friends flag=userinfoservice.selectbyme_his_friend(me.getId(),id);
        if (flag!=null)
        {
        }
        else {
            Friends friends = new Friends();
            friends.setMy_id(me.getId());
            friends.setMy_name(me.getUsername());
            friends.setHis_id(he.getId());
            friends.setHis_name(he.getUsername());
            //两个用户互加好友
            userinfoservice.insertintoFriends(friends);
        }
        //如果还没有加好友，将自动添加好友，1，把我加为他的好友
        Friends flag2=userinfoservice.selectbyme_his_friend(id,me.getId());
        if (flag2!=null)
        {
        }
        else {
            //两个用户互加好友
            Friends friends = new Friends();
            friends.setMy_id(id);
            friends.setMy_name(he.getUsername());
            friends.setHis_id(me.getId());
            friends.setHis_name(me.getUsername());
            userinfoservice.insertintoFriends(friends);
        }

        return "redirect:/stu/friends/list";
    }


    //跳转到我的好友列表
    @RequestMapping("/friends/list")
    public String friends_list(HttpSession session,Model model)
    {
        User user=(User)session.getAttribute("loginuser");
        List<Friends> friends=userinfoservice.selectbyallmy_friends(user.getId());
        model.addAttribute("friends",friends);
        return "student/friends/list";
    }
}